package com.gitee.mocoffee.hclient;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.security.KeyStore;

/**
 * @author lijia
 */
public class KeyStoreKit {
    private KeyStoreKit() {}

    public static KeyStoreKit me = new KeyStoreKit();

    public KeyStore loadKeyStore(File file, String storePass) {
        return loadKeyStore(KeyStore.getDefaultType(), file, storePass);
    }

    public KeyStore loadKeyStore(String type, File file, String storePass) {
        try {
            return loadKeyStore(type, new FileInputStream(file), storePass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public KeyStore loadKeyStore(URL url, String storePass) {
        return loadKeyStore(KeyStore.getDefaultType(), url, storePass);
    }

    public KeyStore loadKeyStore(String type, URL url, String storePass) {
        try {
            return loadKeyStore(type, url.openStream(), storePass);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public KeyStore loadKeyStore(InputStream inputStream, String storePass) {
        return loadKeyStore(KeyStore.getDefaultType(), inputStream, storePass);
    }

    public KeyStore loadKeyStore(String type, InputStream inputStream, String storePass) {
        try {
            KeyStore keyStore = KeyStore.getInstance(type);
            try (InputStream is = inputStream) {
                keyStore.load(is, storePass.toCharArray());
            }
            return keyStore;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
